import socket

from pyspark import SparkConf
from pyspark.sql import SparkSession


class SparkBase:
    _spark_session = None

    @classmethod
    def get_spark(cls):
        cls._spark_session = SparkSession.builder \
            .appName("sparkBase") \
            .master("local[*]") \
            .config("spark.jars",
                    r"C:\Users\govnet\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar") \
            .getOrCreate()



        # # 获取本地 IP（替换为你的实际方法）
        # local_ip = socket.gethostbyname(socket.gethostname())
        # # 创建 SparkSession
        # cls._spark_session = SparkSession.builder \
        #     .appName("sparkBase") \
        #     .master("spark://192.168.1.201:7077") \
        #     .config("spark.driver.host", local_ip) \
        #     .config("spark.driver.port", "0") \
        #     .getOrCreate()  # 自动处理现有实例
        return cls._spark_session

    @classmethod
    def stop_spark(cls):
        if cls._spark_session is not None:
            cls._spark_session.stop()


def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except:
        return "127.0.0.1"
